#include "thread.h"
#include "log.h"

void* thread_fun(void *arg)
{
	Thread *thread = (Thread *)arg;
	thread->_Run();
	return NULL;
}

int Thread::Start()
{
	if (!_is_stopped)
		return 0;

	if (_Prepare() < 0)
		return -1;

	_is_stopped = false;

	int rc;
	if ( (rc = pthread_create(&_id, NULL, thread_fun, this)) != 0)
	{
		ELOG("pthread_create() failed: %d", rc);
		abort();
		return -1;
	}

	return 0;
}

int Thread::Stop()
{
	if (_is_stopped)
		return 0;

	_is_stopped = true;

	void* ret_val = NULL;
	int rc;
	if ( (rc = pthread_join(_id, &ret_val)) != 0)
	{
		ELOG("pthread_join() failed: %d", rc);
		abort();
		return -1;
	}

	_Finish();	
	return 0;
}

void Thread::_Run()
{
	while (!_is_stopped) 
		_Kernel();
}